<!--
 * @Author: your name
 * @Date: 2022-02-15 09:30:20
 * @LastEditTime: 2022-02-17 17:49:26
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \web-vue\src\views\sys\User.vue
-->
<!--  -->
<template>
  <div>
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="用户名" clearable=""></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dialogVisible=true" v-if="hasAuth('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="确定批量删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" slot="reference" :disabled="delBtnStatu" v-if="hasAuth('sys:user:delete')">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table ref="multipleTable" :data="tableData" border stripe tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="头像" width="50">
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>

      <el-table-column label="角色名称">
        <template slot-scope="scope">
          <el-tag size="small" type="info" v-for="item in scope.row.roles" :key="id">{{item.name}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="email" label="邮箱" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="remark" label="手机号" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="statu" label="状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.statu === 1" type="success">正常</el-tag>
          <el-tag size="small" v-else-if="scope.row.statu === 0" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="icon" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="roleHandle(scope.row.id)">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="passwordHandle(scope.row.id,scope.row.username)">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="确定删除吗？" @confirm="delHandle(scope.row.id)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]" :current-page="current" :page-size="size" :total="total">
    </el-pagination>

    <!-- 新增 对话框 -->
    <el-dialog title="新增" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
          <el-alert title="初始密码为888888" :closable="false" type="info" style="line-height: 12px;"></el-alert>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phoneNo">
          <el-input v-model="editForm.remark" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="statu">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')">确定</el-button>
          <el-button @click="resetForm('editForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色 对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="600px">
      <el-form :model="roleForm">
        <el-tree :data="roleTreeData" show-checkbox ref="roleTree" node-key="id" :check-strictly=true :default-expand-all=true :props="defaultProps">
        </el-tree>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="permDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRoleFormHandle('permForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      //搜索
      searchForm: {},
      dialogVisible: false,
      delBtnStatu: true,
      multipleSelection: [],

      //表格
      tableData: {},

      // 分页
      total: 0,
      size: 10,
      current: 1,

      // 新增
      editForm: [],
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        statu: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
      },
      dialogVisible: false,

      // 分配角色
      roleForm: {},
      roleDialogVisible: false,
      roleTreeData: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
    }
  },
  created() {
    this.getUserList()
    this.$axios.get("/sys/role/list").then(res => {
      this.roleTreeData = res.data.data.records
    })
  },
  methods: {
    getUserList() {
      this.$axios.get('/sys/user/list', {
        params: {
          username: this.searchForm.username,
          size: this.size,
          current: this.current,
        }
      }).then(res => {
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    },
    delHandle(id) {
      var ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }

      this.$axios.post("/sys/user/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        });
      })
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      this.delBtnStatu = this.multipleSelection.length == 0
    },
    // 分配角色
    roleHandle(id) {
      this.roleDialogVisible = true
    },
    // 重置密码
    passwordHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$axios.post("/sys/user/repass", id).then(res => {
						this.$message({
							showClose: true,
							message: '恭喜你，操作成功',
							type: 'success',
							onClose: () => {
							}
						});
					})
				})
    },
    // 编辑
    editHandle(id) {
      this.$axios.get('/sys/user/info' + id).then(res => {
        this.editForm = res.data.data
        this.dialogVisible = true
      })
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getUserList()
      console.log(`当前页: ${val}`)
    },

    // 新增
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/sys/user/' + (this.editForm.id ? 'update' : 'save'), this.editForm).then(res => {
            this.$message({
              message: '恭喜你，操作成功!',
              type: 'success',
              // onClose是一个回调
              onClose: () => {
                this.getUserList()
              }
            })

            this.resetForm('editForm')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
      this.editForm = []
    },
    handleClose() {
      this.resetForm('editForm')
    },

    // 分配角色对话框
    submitRoleFormHandle(formName) {
      var roleIds = this.$refs.roleTree.getCheckedKeys()

      this.$axios.post('/sys/user/role/' + this.roleForm.id, roleIds).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getUserList()
          }
        });

        this.roleDialogVisible = false
      })
    },
  }

}
</script>

<style  scoped>
.el-pagination {
  float: right;
  margin-top: 20px;
}
</style>
